package com.umfwechat.lightprogram.controller.my;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.lightprogram.vo.StoreAccountQueryVo;
import com.umfwechat.util.DateTimesUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.StringUtil;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.AgentPerm;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.model.settle.CollectSettleStat;
import com.umpay.sp.service.saas.remote.AgentPermServiceRemote;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.service.settle.remote.SettleStatServiceRemote;
import com.umpay.sp.xml.XmlData;
/**
 * 代理商查询商户接口
 * @author duhao
 *
 */
@Controller
@RequestMapping("/agentSeacherStroe")
public class AgentSeacherStroeController {
	private static Logger logger = LoggerFactory.getLogger(AgentSeacherStroeController.class);

	@Resource
	private StoreInfServiceRemote storeInfServiceRemote;  
	@Resource
	private SettleStatServiceRemote settleStatServiceRemote;
	@Resource
	private AgentPermServiceRemote agentPermServiceRemote;
	/**
	 * 代理商查询商户
	 * @param req
	 * @param resp	 
	 * @return 
	 */
	@RequestMapping(value="/queryStoreByCondition")
	@ResponseBody
	public JSONObject queryStoreByCondition(HttpServletRequest req, HttpServletResponse resp)throws Exception{
		JSONObject json = new JSONObject();
		json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
		json.put(CommonConsts.RETMSG,"成功");
		
		//收集客户端请求数据
		String reqJSON = (String) req.getAttribute(CommonConsts.REQUESTDATA);
		JSONObject param = null;
		try {
			param = JSONObject.fromObject(reqJSON);
		} catch (Exception e1) {
			json.put(CommonConsts.RETCODE, "00434100");
			json.put(CommonConsts.RETMSG,"请求参数不足");
			logger.info("【数据转换异常】 ");
		}
		String loginAgentId = param.optString(CommonConsts.LOGINAGENTID);			 //loginAgentId:登录代理商编号loginUserId
		String agentId = param.optString(CommonConsts.AGENTID,loginAgentId);			 //userId:代理商编号
		String loginUserId = param.optString(CommonConsts.LOGINUSERID);			 //loginAgentId:
		String storeName  = param.optString(CommonConsts.STORENAME);	 //storeName :商户名称
		String storeStatus  = param.optString("storeStatus");			 //storeStatus ：店铺状态 部署中:0 审核中:1 已部署:2 	
		String startDate  = param.optString(CommonConsts.START_DATE);	 //startDate： 开始时间 
		String endDates  = param.optString("endDates");		 //endDate ：结束时间
		
		if(startDate == null || "".equals(startDate) || "null".equals(startDate)){
			startDate = "2017-03-01";
		}
		if(endDates == null ||  "".equals(endDates) ||  "null".equals(endDates)){
			
			endDates = DateTimesUtil.date10();
		}
		String order   = param.optString(CommonConsts.ORDER);			 //order ：排序方式(1交易量／2交易笔数／部署时间)
		String flag    = param.optString(CommonConsts.FLAG);			 //flag  ： 排序1升2降
		
		String pageNo   = param.optString(CommonConsts.PAGE_NO);		 //pageNo  ：页数
		if(StringUtil.isEmpty(pageNo)){
			pageNo=ValueConsts.PAGE_ONE;
		}
		String pageSize =param.optString(CommonConsts.PAGE_SIZE);	//每页条数
		if(StringUtil.isEmpty(pageSize)){
			pageSize=ValueConsts.PAGE_TWENTY;
		}
		Integer startNo = Integer.valueOf(pageSize)*(Integer.valueOf(pageNo)-1);	//计算开始行数
		Integer endNo = Integer.valueOf(pageSize)*Integer.valueOf(pageNo);	//计算结束行数
		//判断是否有操作权限
		/*String assistId =(String) param.get(CommonConsts.LOGINASSISTID);//登录账号
		
		String userId = (String) param.get(CommonConsts.LOGINUSERID);//业务员编号
		if(!"admin".equals(userId)){
			boolean b =getPermission(userId,loginAgentId,assistId,2);	//1:分润查询; 2:代理商商户查询; 3:对账文件获取
			if(!b){
				json.put(CommonConsts.RETCODE, "0001");
				json.put(CommonConsts.RETMSG, "您没有操作权限");
				return json;
			}
		}*/
		
		//获取当前代理商的所有下级代理商信息
		logger.info("【调用查询当前代理商多级关系接口】");
	    Map<String, Object> params = ReqMessageUtil.makeReqCrmMap();
		params.put(CommonConsts.AGENTID, agentId);
		params.put(CommonConsts.RELTYPE, "2");
		Map<String, Object> crmResult = null;
		String retCode = "";
		String agentIds ="";
		Map<String, Object> agentMap  = null;
		try {
			XStream xstream = new XStream(new DomDriver());
			// URL配置文件取 --日志
 			String url=UmfPropModel.INSTANCE.getPropValue("agent.crm.queryAgentRel");
			//调用受理注销用户标识接口---参数
 			logger.info("【查询代理商多级关系接口】入参url：" + url);
			logger.info("【查询代理商多级关系接口】入参params：" + params);
			crmResult =  (Map<String, Object>) com.umfwechat.util.HttpUtil.getResObjPost(url, xstream, params);	
			logger.info("【查询代理商多级关系接口】出参：" + crmResult);				
			if(crmResult==null || crmResult.isEmpty()) {
				logger.info("==★====★★★★★★====★==查询代理商多级关系接口：请求CRM系统失败:查询代理商多级关系接口失败");				
				json.put(CommonConsts.RETCODE, "00434101");
				json.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");	
				return json;
			}
			retCode = (String) crmResult.get(CommonConsts.RETCODE);
			if (!RetCode.SUCCESS.equals(retCode)){
				logger.info("查询代理商多级关系接口失败!");
				json.put(CommonConsts.RETCODE, "00434101");
				json.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");	
				return json;
			}
			Map<String, Object> agentMetaMap =  (Map<String, Object>) crmResult.get("agentMetaMap");
			agentMap =  (Map<String, Object>) crmResult.get("agentMap");
			if( agentMetaMap.get("minLevel") == null ||  agentMetaMap.get("maxLevel") == null){
				logger.info("查询代理商多级关系接口获取参数失败!");
				json.put(CommonConsts.RETCODE, "00434101");
				json.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");	
				return json;
			}
			Integer min = Integer.valueOf( agentMetaMap.get("minLevel").toString()) ;
			Integer max =  Integer.valueOf( agentMetaMap.get("maxLevel").toString()) ; 
			StringBuffer agens = new StringBuffer();//代理商集合
			for(int i = max;i<=min;i++){
				List s  = (List) agentMetaMap.get("agent["+i+"]List");
				for(int j =0 ;j<s.size();j++){
					agens.append("'"+s.get(j)+"',");
				}
			}
			agentIds = agens.toString().substring(0,agens.toString().length()-1);//代理商集合
		} catch (Exception e) {
			logger.error("【调用查询代理商多级关系接口失败!】",e);
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");	
			return json;
		}
		if("1".equals(storeStatus) || "2".equals(storeStatus)){
			//审核中和已部署
			json =  queryDeployde(agentIds,storeName,storeStatus,order,flag,startDate,endDates,startNo,endNo,json,agentMap);
		}else if("0".equals(storeStatus)){
			//部署中(类似自助部署列表)
			json = queryDeploying(agentIds,storeName,startDate,endDates,startNo,endNo,json,agentMap);
		}else if("3".equals(storeStatus)){
			//
			json = querystoreByName(loginUserId,loginAgentId,agentIds,storeName,storeStatus,order,flag,startDate,endDates,startNo,endNo,json,agentMap);
		}
		return json;	
	}




	private JSONObject querystoreByName(String loginUserId,
			String loginAgentId, String agentIds, String storeName,String storeStatus,
			String order,String flag, String startDate, String endDates, Integer startNo, Integer endNo,
			JSONObject result, Map<String, Object> agentMap) {
		
		logger.info("【获取商户昨日交易列表】开始");			
		//查询店铺列表参数		
		ReqMessage reqMsg=ReqMessageUtil.makeSpReq();
		ResMessage queryResMsg = null;	
		if("admin".equals(loginUserId)){
			reqMsg.put(CommonConsts.AGENTIDS,agentIds);//	
		}else{
			reqMsg.put("salesmanId",loginUserId);//
			reqMsg.put("agentId",loginAgentId);//		 
		}						
		if(!"".equals(storeName) && storeName != null){
			reqMsg.put(CommonConsts.STORESHORTNAME,storeName);//代理商商户名称支持模糊查询
		}		 			
		//
		reqMsg.put(CommonConsts.REGISTER_PROCS_STATES,"'06','07','08','09'");	

		//设置昨天的日期
		Calendar cal=Calendar.getInstance();
		cal.add(Calendar.DATE, -1); 
		String yesterDay=DateTimesUtil.date8(cal.getTime());
		//调用查询接口
		logger.info("【获取自助部署列表】请求参数：" + reqMsg);
		queryResMsg = storeInfServiceRemote.getStoreInfList(reqMsg);
		logger.info("【获取自助部署列表】返回参数：" + queryResMsg);
		if(RetCode.SUCCESS.equals(queryResMsg.getRetCode())){
			if(Integer.parseInt(queryResMsg.getResMap().get(CommonConsts.TOTAL_SIZE).toString())>0){
				List<StoreInf> storeInfList=(List<StoreInf>)queryResMsg.getResMap().get(XmlData.STORE_INF_LIST);	//获取商铺列表
				StringBuilder sb=new StringBuilder();
				for(int i=0;i<storeInfList.size();i++){
					sb.append("'");
					sb.append(storeInfList.get(i).getStoreId());
					sb.append("'");
					sb.append(",");
				}
				//查询金额笔数汇总参数
				ReqMessage querySumReqMsg=ReqMessageUtil.makeSpReq();
				ResMessage querySumResMsg = new ResMessage();
				//设置汇总查询的参数
				String orderName = CommonConsts.MERID_;	//默认按部署时间排序（店铺编号越大，部署时间越晚）
				if("1".equals(order)){	//交易量
					orderName = CommonConsts.AMOUNT_;
				}else if ("2".equals(order)) {	//交易笔数
					orderName = CommonConsts.LOANNUM_;
				}
				if ("1".equals(flag)) {	//升序
					orderName = orderName + " " + CommonConsts.ASC_;
				}else if ("2".equals(flag)) {	//降序
					orderName = orderName + " " + CommonConsts.DESC_;
				}
				querySumReqMsg.put(CommonConsts.YESTERDAY,yesterDay);
				//querySumReqMsg.put("startNo",startNo.toString());
				//querySumReqMsg.put("endNo",endNo.toString());
				querySumReqMsg.put(CommonConsts.ORDERNAME,orderName);
				querySumReqMsg.put(CommonConsts.MERIDS,sb.toString().substring(0,sb.toString().length()-1));
				//查询统计
				logger.info("【获取昨日交易列表】请求参数：" + querySumReqMsg);
				try{
					querySumResMsg=settleStatServiceRemote.collectSettleStatsByMerIdYesterday(querySumReqMsg);
				}catch(Exception e){
					result.put(CommonConsts.RETCODE, "00434101");
					result.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");
					logger.error("【获取昨日交易列表】接口异常");
				}				
				logger.info("【获取昨日交易列表】返回参数：" + querySumResMsg);
				if(querySumResMsg.getRetCode().equals(RetCode.SUCCESS)){
					List<CollectSettleStat> collectSettleStatList = (List<CollectSettleStat>)querySumResMsg.getValue("collectSettleStatList");
					List<StoreAccountQueryVo> storeList=new ArrayList<StoreAccountQueryVo>();
					
					/**
					 * 获取T_SETTLE_STAT表中所有统计的数据
					 */
					for (int i = 0; i < collectSettleStatList.size(); i++) {
						for (int j = 0; j < storeInfList.size(); j++) {
							StoreInf storInf=storeInfList.get(j);
							if (collectSettleStatList.get(i).getMerId().equals(storInf.getStoreId())) {
								StoreAccountQueryVo saqVo=new StoreAccountQueryVo();
								saqVo.setStoreId(storInf.getStoreId());
								saqVo.setStoreName(storInf.getStoreShortName());
								saqVo.setPosReportId(storInf.getPosReportId());	//POS报备编号
								saqVo.setCreateDate(DateTimesUtil.date10(storInf.getIntime()));
								saqVo.setSumAmount(collectSettleStatList.get(i).getAmount());
								saqVo.setSumNum(collectSettleStatList.get(i).getLoanNum());
								//增加代理商编号
								saqVo.setAgentId(storInf.getAgentId());
								storeInfList.remove(j);
								storeList.add(saqVo);
							}
						}
					}
					
					/**
					 * 没有数据的店铺，设置为0，并且补充到集合中
					 */
					for (int i = 0; i < storeInfList.size(); i++) {
						StoreInf storInf=storeInfList.get(i);
						StoreAccountQueryVo saqVo=new StoreAccountQueryVo();
						saqVo.setStoreId(storInf.getStoreId());
						saqVo.setStoreName(storInf.getStoreShortName());
						saqVo.setPosReportId(storInf.getPosReportId());	//POS报备编号
						//增加代理商编号
						saqVo.setAgentId(storInf.getAgentId());
						saqVo.setCreateDate(DateTimesUtil.date10(storInf.getIntime()));
						saqVo.setSumAmount("0");
						saqVo.setSumNum("0");
						storeList.add(saqVo);
					}
					
					/**
					 * 对要返回的数据进行大排序
					 */
					if (orderName.contains(CommonConsts.MERID_)) {	//如果是MERID，则按部署时间排序
						if("1".equals(flag)){
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
									try {
										Date dt1 = format.parse(o1.getCreateDate());
										Date dt2 = format.parse(o2.getCreateDate());
										if (dt1.getTime() > dt2.getTime()) {
											return 1;
										} else if (dt1.getTime() < dt2.getTime()) {
											return -1;
										} else {
											return 0;
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
									return 0;
								}
							});
						}else {
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
									try {
										Date dt1 = format.parse(o1.getCreateDate());
										Date dt2 = format.parse(o2.getCreateDate());
										if (dt1.getTime() < dt2.getTime()) {
											return 1;
										} else if (dt1.getTime() > dt2.getTime()) {
											return -1;
										} else {
											return 0;
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
									return 0;
								}
							});
						}
					}else if (orderName.contains("AMOUNT")) {	//如果是AMOUNT，则按交易量排序
						if ("1".equals(flag)) {
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									return o1.getSumAmount().compareTo(o2.getSumAmount());
								}
							});
						}else {
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									return o2.getSumAmount().compareTo(o1.getSumAmount());
								}
							});
						}
					}else if (orderName.contains("LOANNUM")) {	//如果是LOANNUM，则按交易笔数排序
						if ("1".equals(flag)) {
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									return o1.getSumNum().compareTo(o2.getSumNum());
								}
							});
						}else {
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									return o2.getSumNum().compareTo(o1.getSumNum());
								}
							});
						}
					}
					
					/**
					 * 对排序好的数据进行分页
					 */
					List<StoreAccountQueryVo> list=new ArrayList<StoreAccountQueryVo>();
					for (int i = startNo; i < storeList.size(); i++) {
						if (i == endNo) {
							break;
						}
						list.add(storeList.get(i));
					}
					/**
					 * 分页之后获取代理商简称
					 */
					for(int i =0;i<list.size();i++){	
						if(agentMap.containsKey(list.get(i).getAgentId())){	
							String id  = list.get(i).getAgentId();
							Map<String,String> agentDate = (Map<String,String>) agentMap.get(id);	
							list.get(i).setAgentShortName(agentDate.get("agentShortName"));
						}else{
							logger.info(" 查询代理商多级关系接口：没有此代理商的基本信息");
						}
					}
					result.put(CommonConsts.RETCODE,"0000");
					result.put(CommonConsts.RETMSG,"成功");
					result.put(CommonConsts.STORE_LIST, list);
				}else{					
					result.put(CommonConsts.RETCODE, "00434101");
					result.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
					logger.error("【【获取昨日交易列表】异常");
				}
			}else{
				//商铺列表为0
				result.put(CommonConsts.RETCODE, "00434108");
				result.put(CommonConsts.RETMSG,"商铺列表为空");
			}
		}else{
			result.put(CommonConsts.RETCODE, "00434101");
			result.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");
			logger.error("【获取昨日交易列表】异常");
		}
		return result;
	}




	private JSONObject queryDeploying(String agentIds, String storeName,
			 String startDate, String endDates, Integer startNo, Integer endNo,
			JSONObject json,Map<String, Object> agentMap) {
			// 部署中(类似自助部署列表)
		ReqMessage req = ReqMessageUtil.makeSpReq();
		ResMessage res = null;	
		req.put(CommonConsts.AGENTIDS,agentIds);//代理商编号集合		
		req.put(CommonConsts.INTIMESTART,startDate);//开始时间
		req.put(CommonConsts.INTIMEEND,endDates);//结束时间
		req.put(CommonConsts.START_NO,startNo.toString());//开始页
		req.put(CommonConsts.END_NO,endNo.toString());//结束
		if(!"".equals(storeName) && storeName != null){
			req.put(CommonConsts.STORE_SHORT_NAME,storeName);//代理商商户名称支持模糊查询
		}	

		//立马付状态：02待提交店铺；03待上传照片；04待开通产品；05待邀请商户；10待商户签约；06-待修改；11-待审核；12-待报备；13-待配置银商关系	
		req.put(CommonConsts.REGISTER_PROCS_STATES,"'02','03','04','05','06','10','11','12','13'");
	
		try {
			logger.info("【获取商户列表】请求参数：" + req);
			res = storeInfServiceRemote.getStoreInfList(req);
			logger.info("【获取商户列表】返回参数：" + res);
		} catch (Exception e) {

			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
			logger.error("【获取商户列表】异常" , e);
		
		}
		if (RetCode.SUCCESS.equals(res.getRetCode())) {
			if(Integer.parseInt(res.getResMap().get(CommonConsts.TOTAL_SIZE).toString())>0){
				List<StoreInf> storeInfs = (List<StoreInf>) res.getResMap().get(CommonConsts.STOREINF_LIST);
				List<Map<String, String>> list = new ArrayList<Map<String, String>>();
				for (int i = 0; i < storeInfs.size(); i++) {
					Map<String, String> map = new HashMap<String, String>();
					if(StringUtil.isEmpty(storeInfs.get(i).getStoreShortName())){
						map.put(CommonConsts.STORE_SHORT_NAME, "名称待填写");
					}else {
						map.put(CommonConsts.STORE_SHORT_NAME, storeInfs.get(i).getStoreShortName());
					}
					map.put(CommonConsts.PAYEENAME, storeInfs.get(i).getPayeeName());
					map.put(CommonConsts.PAYEEMOBILE, storeInfs.get(i).getPayeeMobileId());
					map.put(CommonConsts.STATE, storeInfs.get(i).getRegisterProcsState());
					map.put(CommonConsts.STOREID, storeInfs.get(i).getStoreId());
					map.put("type", storeInfs.get(i).getType());
					
					//获取代理商简称和编号
					map.put(CommonConsts.AGENTID, storeInfs.get(i).getAgentId());
					if(agentMap.containsKey(storeInfs.get(i).getAgentId())){
						Map<String,String> agentDate = (Map<String,String>) agentMap.get(storeInfs.get(i).getAgentId());
						map.put(CommonConsts.AGENT_SHORT_NAME,agentDate.get("agentShortName"));
					}else{
						logger.error(" 查询代理商多级关系接口：没有此代理商的基本信息");
					}
					
					list.add(map);
				}
				json.put(CommonConsts.STORE_LIST, list);
				json.put(CommonConsts.RETCODE, RetCode.SUCCESS);
				json.put(CommonConsts.RETMSG, "成功");
			}else{
				json.put(CommonConsts.RETCODE, "00434108");
				json.put(CommonConsts.RETMSG,"商铺列表为空");
			}
			
		}else {
			json.put(CommonConsts.RETCODE, "00434101");
			json.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");
			logger.error("【获取商户列表】异常");
			
		}
		return json;
	}




	private JSONObject queryDeployde(String agentIds, String storeName,String storeStatus,
			String order,String flag, String startDate, String endDates, Integer startNo, Integer endNo,
			JSONObject result, Map<String, Object> agentMap) {
		logger.info("【获取商户昨日交易列表】开始");
	
		
		//查询店铺列表参数		
		ReqMessage reqMsg=ReqMessageUtil.makeSpReq();
		ResMessage queryResMsg = null;	
		reqMsg.put(CommonConsts.AGENTIDS,agentIds);//代理商编号集合		
		reqMsg.put(CommonConsts.INTIMESTART,startDate);//开始时间
		reqMsg.put(CommonConsts.INTIMEEND,endDates);//结束时间	
		if(!"".equals(storeName) && storeName != null){
			reqMsg.put(CommonConsts.STORESHORTNAME,storeName);//代理商商户名称支持模糊查询
		}		 
		if("1".equals(storeStatus)){
			//审核中07/自动审核通过待审查09/待复查  
			reqMsg.put(CommonConsts.REGISTER_PROCS_STATES,"'07','09'");
		}else if("2".equals(storeStatus)){
			//已部署08/复审开通成功 
			reqMsg.put(CommonConsts.REGISTER_PROCS_STATES,"'08'");
		}

		//设置昨天的日期
		Calendar cal=Calendar.getInstance();
		cal.add(Calendar.DATE, -1); 
		String yesterDay=DateTimesUtil.date8(cal.getTime());
		//调用查询接口
		logger.info("【获取自助部署列表】请求参数：" + reqMsg);
		queryResMsg = storeInfServiceRemote.getStoreInfList(reqMsg);
		logger.info("【获取自助部署列表】返回参数：" + queryResMsg);
		if(RetCode.SUCCESS.equals(queryResMsg.getRetCode())){
			if(Integer.parseInt(queryResMsg.getResMap().get(CommonConsts.TOTAL_SIZE).toString())>0){
				List<StoreInf> storeInfList=(List<StoreInf>)queryResMsg.getResMap().get(XmlData.STORE_INF_LIST);	//获取商铺列表
				StringBuilder sb=new StringBuilder();
				for(int i=0;i<storeInfList.size();i++){
					sb.append("'");
					sb.append(storeInfList.get(i).getStoreId());
					sb.append("'");
					sb.append(",");
				}
				//查询金额笔数汇总参数
				ReqMessage querySumReqMsg=ReqMessageUtil.makeSpReq();
				ResMessage querySumResMsg = new ResMessage();
				//设置汇总查询的参数
				String orderName = CommonConsts.MERID_;	//默认按部署时间排序（店铺编号越大，部署时间越晚）
				if("1".equals(order)){	//交易量
					orderName = CommonConsts.AMOUNT_;
				}else if ("2".equals(order)) {	//交易笔数
					orderName = CommonConsts.LOANNUM_;
				}
				if ("1".equals(flag)) {	//升序
					orderName = orderName + " " + CommonConsts.ASC_;
				}else if ("2".equals(flag)) {	//降序
					orderName = orderName + " " + CommonConsts.DESC_;
				}
				querySumReqMsg.put(CommonConsts.YESTERDAY,yesterDay);
				//querySumReqMsg.put("startNo",startNo.toString());
				//querySumReqMsg.put("endNo",endNo.toString());
				querySumReqMsg.put(CommonConsts.ORDERNAME,orderName);
				querySumReqMsg.put(CommonConsts.MERIDS,sb.toString().substring(0,sb.toString().length()-1));
				//查询统计
				logger.info("【获取昨日交易列表】请求参数：" + querySumReqMsg);
				try{
					querySumResMsg=settleStatServiceRemote.collectSettleStatsByMerIdYesterday(querySumReqMsg);
				}catch(Exception e){
					result.put(CommonConsts.RETCODE, "00434101");
					result.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");
					logger.error("【获取昨日交易列表】接口异常");
				}				
				logger.info("【获取昨日交易列表】返回参数：" + querySumResMsg);
				if(querySumResMsg.getRetCode().equals(RetCode.SUCCESS)){
					List<CollectSettleStat> collectSettleStatList = (List<CollectSettleStat>)querySumResMsg.getValue("collectSettleStatList");
					List<StoreAccountQueryVo> storeList=new ArrayList<StoreAccountQueryVo>();
					
					/**
					 * 获取T_SETTLE_STAT表中所有统计的数据
					 */
					for (int i = 0; i < collectSettleStatList.size(); i++) {
						for (int j = 0; j < storeInfList.size(); j++) {
							StoreInf storInf=storeInfList.get(j);
							if (collectSettleStatList.get(i).getMerId().equals(storInf.getStoreId())) {
								StoreAccountQueryVo saqVo=new StoreAccountQueryVo();
								saqVo.setStoreId(storInf.getStoreId());
								saqVo.setStoreName(storInf.getStoreShortName());
								saqVo.setCreateDate(DateTimesUtil.date10(storInf.getIntime()));
								saqVo.setSumAmount(collectSettleStatList.get(i).getAmount());
								saqVo.setSumNum(collectSettleStatList.get(i).getLoanNum());
								//增加代理商编号
								saqVo.setAgentId(storInf.getAgentId());
								storeInfList.remove(j);
								storeList.add(saqVo);
							}
						}
					}
					
					/**
					 * 没有数据的店铺，设置为0，并且补充到集合中
					 */
					for (int i = 0; i < storeInfList.size(); i++) {
						StoreInf storInf=storeInfList.get(i);
						StoreAccountQueryVo saqVo=new StoreAccountQueryVo();
						saqVo.setStoreId(storInf.getStoreId());
						saqVo.setStoreName(storInf.getStoreShortName());
						//增加代理商编号
						saqVo.setAgentId(storInf.getAgentId());
						saqVo.setCreateDate(DateTimesUtil.date10(storInf.getIntime()));
						saqVo.setSumAmount("0");
						saqVo.setSumNum("0");
						storeList.add(saqVo);
					}
					
					/**
					 * 对要返回的数据进行大排序
					 */
					if (orderName.contains(CommonConsts.MERID_)) {	//如果是MERID，则按部署时间排序
						if("1".equals(flag)){
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
									try {
										Date dt1 = format.parse(o1.getCreateDate());
										Date dt2 = format.parse(o2.getCreateDate());
										if (dt1.getTime() > dt2.getTime()) {
											return 1;
										} else if (dt1.getTime() < dt2.getTime()) {
											return -1;
										} else {
											return 0;
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
									return 0;
								}
							});
						}else {
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
									try {
										Date dt1 = format.parse(o1.getCreateDate());
										Date dt2 = format.parse(o2.getCreateDate());
										if (dt1.getTime() < dt2.getTime()) {
											return 1;
										} else if (dt1.getTime() > dt2.getTime()) {
											return -1;
										} else {
											return 0;
										}
									} catch (Exception e) {
										e.printStackTrace();
									}
									return 0;
								}
							});
						}
					}else if (orderName.contains("AMOUNT")) {	//如果是AMOUNT，则按交易量排序
						if ("1".equals(flag)) {
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									return o1.getSumAmount().compareTo(o2.getSumAmount());
								}
							});
						}else {
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									return o2.getSumAmount().compareTo(o1.getSumAmount());
								}
							});
						}
					}else if (orderName.contains("LOANNUM")) {	//如果是LOANNUM，则按交易笔数排序
						if ("1".equals(flag)) {
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									return o1.getSumNum().compareTo(o2.getSumNum());
								}
							});
						}else {
							Collections.sort(storeList, new Comparator<StoreAccountQueryVo>() {
								@Override
								public int compare(StoreAccountQueryVo o1, StoreAccountQueryVo o2) {
									return o2.getSumNum().compareTo(o1.getSumNum());
								}
							});
						}
					}
					
					/**
					 * 对排序好的数据进行分页
					 */
					List<StoreAccountQueryVo> list=new ArrayList<StoreAccountQueryVo>();
					for (int i = startNo; i < storeList.size(); i++) {
						if (i == endNo) {
							break;
						}
						list.add(storeList.get(i));
					}
					/**
					 * 分页之后获取代理商简称
					 */
					for(int i =0;i<list.size();i++){	
						if(agentMap.containsKey(list.get(i).getAgentId())){	
							String id  = list.get(i).getAgentId();
							Map<String,String> agentDate = (Map<String,String>) agentMap.get(id);	
							list.get(i).setAgentShortName(agentDate.get("agentShortName"));
						}else{
							logger.info(" 查询代理商多级关系接口：没有此代理商的基本信息");
						}
					}
					result.put(CommonConsts.RETCODE,"0000");
					result.put(CommonConsts.RETMSG,"成功");
					result.put(CommonConsts.STORE_LIST, list);
				}else{					
					result.put(CommonConsts.RETCODE, "00434101");
					result.put(CommonConsts.RETMSG, "服务器异常，请稍后再试");
					logger.error("【【获取昨日交易列表】异常");
				}
			}else{
				//商铺列表为0
				result.put(CommonConsts.RETCODE, "00434108");
				result.put(CommonConsts.RETMSG,"商铺列表为空");
			}
		}else{
			result.put(CommonConsts.RETCODE, "00434101");
			result.put(CommonConsts.RETMSG,"服务器异常，请稍后再试");
			logger.error("【获取昨日交易列表】异常");
		}
		return result;
	}
	/**
	 * @param salesmanId业务员名称
	 * @param agentId代理商编号
	 * @param assistId登录账号
	 * @param type菜单类型(1:分润查询; 2:代理商商户查询; 3:对账文件获取)
	 * @return
	 */
	public boolean getPermission(String salesmanId, String agentId, String assistId, Integer type){
		 com.umpay.sp.model.common.ReqMessage reqMess = ReqMessageUtil.makeSpReq();
		 reqMess.put(CommonConsts.SALESMANID, salesmanId);
		 reqMess.put(CommonConsts.AGENTID,agentId);
		 reqMess.put(CommonConsts.ASSISTID,assistId);
		 ResMessage res = null;
		 try {
			logger.info("【获取代理商权限控制接口】输入参数：" + reqMess);
			res = agentPermServiceRemote.getAgentPermByPri(reqMess);
			logger.info("【获取代理商权限控制接口】输出参数：" + res);
		} catch (Exception e) {
			return false;
		}
		String retCode = res.getRetCode();
		if (!RetCode.SUCCESS.equals(retCode)) {
			return false;
		}
		AgentPerm agentPerm = (AgentPerm) res.getResMap().get("agentPerm");
		if (agentPerm == null) {
			return false;
		}
		if(type == 1){	//分润查询权限
			if("1".equals(agentPerm.getSearchProfitPerm())){
				return true;
			}
		}
		if(type == 2){	//代理商商户查询权限
			if("1".equals(agentPerm.getSearchStorePerm())){
				return true;
			}
		}
		if(type == 3){	//对账文件获取权限
			if("1".equals(agentPerm.getFetchBillDocPerm())){
				return true;
			}
		}
		return false;
	}
}
